package com.colter.project.sample.test.execute;

import com.colter.project.util.file.FileUtil;
import com.colter.project.util.ip.IPUtil;
import com.colter.project.util.string.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class WeekPlan {
	public static void main(String[] args) throws IOException {
		List<Plan> list = getPlanFromTxt();
		List<Bind> list2 = changeListToBind(list);
		System.out.println(list);
		System.out.println(list2);
		createPlan(list2);
	}

	/**
	 * 模板后缀：计划模板.xlsx 生成格式：MM-dd.xlsx 内容： 第一列 日期 第二列 计划1 第四列 计划2
	 *  64-51-06-5A-A0-67
	 * @param list
	 */
	public static void createPlan(List<Bind> list) {
		String prefix = "D:\\OneDrive\\每周计划\\";
		String suffix = "计划模板.xlsx";
		
		String mac = IPUtil.getLocalMac();
		if(!mac.equalsIgnoreCase("64-51-06-5A-A0-67")){
			prefix = "F:\\OneDrive\\每周计划\\";
		}
		

		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		SimpleDateFormat sd = new SimpleDateFormat("MM-dd", Locale.US);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		String sSuffix = sd.format(cal.getTime());

		String outPath = prefix + sSuffix + ".xlsx";

		String filePath = prefix + suffix;
		Workbook wb = null;
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;

		boolean isXlsx = filePath.endsWith("xlsx");
		try {
			if (isXlsx) {
				wb = new XSSFWorkbook(new FileInputStream(filePath));
			} else {
				wb = new HSSFWorkbook(new FileInputStream(filePath));
			}
			CellStyle cellStyle= wb.createCellStyle();    
			cellStyle.setWrapText(true);
			cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
			cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
			cellStyle.setBorderBottom(CellStyle.BORDER_THIN); //下边框    
			cellStyle.setBorderLeft(CellStyle.BORDER_THIN);//左边框    
			cellStyle.setBorderTop(CellStyle.BORDER_THIN);//上边框    
			cellStyle.setBorderRight(CellStyle.BORDER_THIN);//右边框  
			sheet = wb.getSheetAt(0);
			int i = 1;
			while (i - 1 < list.size()) {
				
				Font font2 = wb.createFont();  
				CellStyle cellStyle2= wb.createCellStyle();    
				cellStyle2.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
				cellStyle2.setAlignment(CellStyle.ALIGN_CENTER);
				cellStyle2.setBorderBottom(CellStyle.BORDER_THIN); //下边框    
				cellStyle2.setBorderLeft(CellStyle.BORDER_THIN);//左边框    
				cellStyle2.setBorderTop(CellStyle.BORDER_THIN);//上边框    
				cellStyle2.setBorderRight(CellStyle.BORDER_THIN);//右边框  
				
				sheet = wb.getSheetAt(0);
				
				Bind bind = list.get(i - 1);
				row = sheet.getRow(i);

				//在要换行处添加\n就可以换行了
				cell = row.getCell(0);
				cell.setCellValue(bind.start);
				cell.setCellStyle(cellStyle); 


				cell = row.getCell(1);
				cell.setCellValue(bind.plan1);
				if(!StringUtils.isBlank(bind.plan1) && getLength(bind.plan1) > 17){
					cell.setCellStyle(changeStyle(font2, cellStyle2, bind.plan1));
				}
				
				cell = row.getCell(2);
				cell.setCellValue(bind.blank1);

				cell = row.getCell(3);
				cell.setCellValue(bind.plan2);
				if(!StringUtils.isBlank(bind.plan2) && getLength(bind.plan2) > 17){
					cell.setCellStyle(changeStyle(font2, cellStyle2, bind.plan2));
				}


				cell = row.getCell(4);
				cell.setCellValue(bind.blank2);

				i++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 输出Excel文件
		FileOutputStream output;
		try {
			output = new FileOutputStream(outPath);
			wb.write(output);
			output.flush();
			wb.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	private static int getLength(String str){
		if(StringUtils.isBlank(str))
			return 0;
		int english = 0;
		int chinese = 0;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if(isChinese(c)){
				chinese ++ ;
			}else{
				english ++;
			}
		}
		return chinese + english/2 + 1;
	}
	
	private static boolean isChinese(char c) {
	      return c >= 0x4E00 &&  c <= 0x9FA5;// 根据字节码判断
	}
	
	/**
	 * 11号17个字
	 * 10 20
	 * 9	22
	 * 8	24
	 * 7
	 * @param cellStyle
	 * @param str
	 * @return
	 */
	private static CellStyle changeStyle(Font font,CellStyle cellStyle,String str){
		int length = getLength(str);
		if(length > 17 && length <= 20){
			font.setFontHeightInPoints((short) 10);
		}else if(length > 20 && length <= 22){
			font.setFontHeightInPoints((short) 9);
		}else if(length > 22 && length <= 24){
			font.setFontHeightInPoints((short) 8);
		}else if(length > 24){
			font.setFontHeightInPoints((short) 6);
		}
		font.setFontName("宋体");
		cellStyle.setFont(font);
		cellStyle.setAlignment(CellStyle.ALIGN_LEFT);
		return cellStyle;
	}

	public static List<Bind> changeListToBind(List<Plan> list) {
		List<Bind> result = new ArrayList<>();
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		SimpleDateFormat sd = new SimpleDateFormat("MM月dd日 \n EEEE",Locale.CHINA);
		for (Plan plan : list) {
			List<String> pList = plan.getList();
			int size = pList.size();
			for (int i = 0; i < size && i < 6; i++) {
				Bind bind = new Bind();
				bind.start = sd.format(cal.getTime());
				bind.plan1 = (i+1) + ":" + pList.get(i);
				bind.blank1 = "";
				if (i + 6 < size) {
					bind.plan2 = (i+1 + 6) + ":" + pList.get(i + 6);
					bind.blank2 = "";
				}
				result.add(bind);
			}
			//补全空格
			if(6 - size > 0){
				for(int i = 0; i < 6-size;i++){
					result.add(new Bind());
				}
			}
			
			cal.add(Calendar.DAY_OF_WEEK, 1);
			result.add(new Bind());
		}
		return result;
	}

	public static List<Plan> getPlanFromTxt() throws IOException {
		List<String> weeks = new ArrayList<>();
		byte[] bytes = new byte[]{-17, -69, -65, -27, -111, -88, -28, -72, -128};
		weeks.add(new String(bytes));
		weeks.add("周一");
		weeks.add("周二");
		weeks.add("周三");
		weeks.add("周四");
		weeks.add("周五");
		weeks.add("周六");
		weeks.add("周日");

		String prefix = "D:\\OneDrive\\每周计划\\";
		String suffix = "每周计划.txt";
		
		String mac = IPUtil.getLocalMac();
		if(!mac.equalsIgnoreCase("64-51-06-5A-A0-67")){
			prefix = "F:\\OneDrive\\每周计划\\";
		}
		
		//back up
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		SimpleDateFormat sd = new SimpleDateFormat("MM-dd",Locale.US);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		Calendar cal2 = Calendar.getInstance();
		
		String dateStr = sd.format(cal2.getTime());
		String backUp =prefix+"原稿 "+dateStr+"-temp.txt"; 
		if(cal.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)){
			 backUp = prefix+dateStr+".txt";
		}
		
		String filePath = prefix+suffix;
		if(!new File(backUp).exists()){
			FileUtil.copyFile(filePath, backUp);
		}
		
		List<Plan> list = new ArrayList<>();
		BufferedReader bf = new BufferedReader(new FileReader(new File(prefix + suffix)));

		Plan plan = new Plan();
		List<String> pList = new ArrayList<>();
		String temp = null;
		while ( (temp = bf.readLine())!= null) {
			if (weeks.contains(temp)) {
				if (pList.size() != 0) {
					plan.setList(pList);
					list.add(plan);
					// reset pList
					plan = new Plan();
					pList = new ArrayList<>();
				}
			} else {
				if (StringUtils.isBlank(temp)) {
					continue;
				}
				pList.add(temp);
			}
		}

		// add the last plan
		if (pList.size() != 0) {
			plan.setList(pList);
			list.add(plan);
		}

		bf.close();

		return list;
	}
}

class Plan {
	private List<String> list;

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	} 

	@Override
	public String toString() {
		return "Plan [list=" + list + "]";
	}

}

class Bind {
	public String start;
	public String plan1;
	public String blank1;
	public String plan2;
	public String blank2;

	@Override
	public String toString() {
		return "Bind [start=" + start + ", plan1=" + plan1 + ", blank1=" + blank1 + ", plan2=" + plan2 + ", blank2="
				+ blank2 + "]";
	}

}
